/*
 * IntegrationHelper.java
 *
 * Copyright 2007, 2008 Tiberiumlabs
 *
 * This file is part of Tiberiumlabs Lailaps.
 *
 * Tiberiumlabs Lailaps is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Tiberiumlabs Lailaps is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.tiberiumlabs.lailaps.actions.system;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ResourceBundle;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.border.EmptyBorder;
import org.tiberiumlabs.lailaps.actions.AbstractResourcedAction;
import org.tiberiumlabs.lailaps.gui.GUIFactory;
import org.tiberiumlabs.lailaps.gui.elements.TableColumnModel;
import org.tiberiumlabs.lailaps.resources.ImageLoader;
import org.tiberiumlabs.swing.DesktopToolkit;

/**
 *
 * @author <a href="mailto:paranoid.tiberiumlabs@gmail.com">Paranoid</a>
 */
public class SelectColumnsAction extends AbstractResourcedAction {

    private boolean[] showFlags = null;
    private JCheckBox[] showBoxes = null;

    private JDialog dialog = null;
    private TableColumnModel tableColumnModel = (TableColumnModel)mediator.getGuiBuilder().getTable().getColumnModel();

    public SelectColumnsAction() {
        putValue(NAME, bundle.getString("columnselector.name"));
        putValue(SHORT_DESCRIPTION, bundle.getString("columnselector.short"));
        putValue(LONG_DESCRIPTION, bundle.getString("columnselector.long"));
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        prepare();
        checkCurrentColumns();
        construct();
    }

    private void prepare() {
        int columnsCount = 11;
        showFlags = new boolean[columnsCount];
        showBoxes = new JCheckBox[columnsCount];

        ResourceBundle boxesBundle = ResourceBundle.getBundle("org/tiberiumlabs/lailaps/resources/messages/table");
        String[] boxLabels = {boxesBundle.getString("field.status"), boxesBundle.getString("field.url"),
                              boxesBundle.getString("field.filename"), boxesBundle.getString("field.path"),
                              boxesBundle.getString("field.completed"), boxesBundle.getString("field.speed"),
                              boxesBundle.getString("field.fullsize"), boxesBundle.getString("field.elapsed"),
                              boxesBundle.getString("field.estimated"), boxesBundle.getString("field.percent"),
                              boxesBundle.getString("field.sizeprogress")};

        for (int i = 0; i < 11; i++) {
            showFlags[i] = false;
            showBoxes[i] = new JCheckBox(boxLabels[i]);
        }
    }

    private void checkCurrentColumns() {
        int[] columnOrder = tableColumnModel.getColumnsOrder();
        if (columnOrder != null && columnOrder.length > 0) {
            for (int i = 0; i < columnOrder.length; i = i+2) {
                showFlags[columnOrder[i]] = true;
                showBoxes[columnOrder[i]].setSelected(true);
            }
        }
    }

    private void construct() {

        final JPanel optionsPane = GUIFactory.createVerticalBoxPanel();
        optionsPane.setDoubleBuffered(true);
        for (int i = 0; i < showBoxes.length; i++) {
            optionsPane.add(showBoxes[i]);
            optionsPane.add(getStrut());
        }
        optionsPane.setBorder(new EmptyBorder(8, 10, 4, 6) {

            @Override
            public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
                super.paintBorder(c, g, x, y, width, height);
                    int w = width-1;
                    int h = height-1;

                    g.translate(x, y);

                    g.setColor(c.getBackground().darker());
                    //g.drawLine(0, 0, w, 0);
                    g.drawLine(0, h-1, w, h-1);

                    g.setColor(c.getBackground().brighter());
                    //g.drawLine(0, 1, w, 1);
                    g.drawLine(0, h, w, h);

                    g.translate(-x, -y);
            }

        });

        JButton applyButton = new JButton(new ApplyButtonAction());
        JButton closeButton = new JButton(new CloseButtonAction());
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
        buttonPanel.add(applyButton);
        buttonPanel.add(Box.createHorizontalStrut(3));
        buttonPanel.add(closeButton);
        buttonPanel.setBorder(new EmptyBorder(4, 2, 4, 4));

        JPanel contentPane = new JPanel(new BorderLayout());
        contentPane.add(optionsPane, BorderLayout.CENTER);
        contentPane.add(buttonPanel, BorderLayout.SOUTH);

        // we dont need to check for visibility of main window here, because we cant even invoke this action without main window visible.
        dialog = new JDialog(mediator.getGuiBuilder().getMainWindow(), bundle.getString("columnselector.name"), true);
        dialog.setContentPane(contentPane);
        dialog.pack();
        dialog.setMinimumSize(dialog.getSize());
        //dialog.setSize((int)(dialog.getWidth()*1.5), dialog.getHeight());

        dialog.getRootPane().setDefaultButton(applyButton);
        dialog.getRootPane().registerKeyboardAction(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);

        dialog.setLocation(DesktopToolkit.getWindowLocation(dialog.getSize()));
        dialog.setVisible(true);
    }

    private final Component getStrut() {
        return Box.createVerticalStrut(5);
    }

    private void closeDialog() {
        if (dialog != null) {
            dialog.dispose();
            dialog = null;
        }
    }

    private void applySelection() {
        for (int i = 0; i < showBoxes.length; i++) {
            // checking values from checkboxes vs original:
            if (showBoxes[i].isSelected() != showFlags[i]) {
                if (showBoxes[i].isSelected()) {
                    // if changed and selected - adding:
                    tableColumnModel.addColumn(i);
                }
                else {
                    // if changed and unselected - removing:
                    tableColumnModel.removeColumn(i);
                }
            }
        }

    }

    private class CloseButtonAction extends AbstractResourcedAction {

        public CloseButtonAction() {
            putValue(NAME, bundle.getString("columnselector.close.name"));
            putValue(SHORT_DESCRIPTION, bundle.getString("columnselector.close.short"));
            putValue(LONG_DESCRIPTION, bundle.getString("columnselector.close.long"));
            putValue(SMALL_ICON, ImageLoader.getButtonCancelIcon());
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            closeDialog();
        }

    }

    private class ApplyButtonAction extends AbstractResourcedAction {

        public ApplyButtonAction() {
            putValue(NAME, bundle.getString("columnselector.apply.name"));
            putValue(SHORT_DESCRIPTION, bundle.getString("columnselector.apply.short"));
            putValue(LONG_DESCRIPTION, bundle.getString("columnselector.apply.long"));
            putValue(SMALL_ICON, ImageLoader.getButtonOkIcon());
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            applySelection();
            closeDialog();
        }

    }

}
